Find Perfect Numbers in a Range

Theory:

A perfect number is a positive integer that is equal to the sum of its proper divisors (excluding itself).

Python Code:

def is_perfect_number(number):
    if number <= 0:
        return False
    divisor_sum = sum(divisor for divisor in range(1, number) if number % divisor == 0)
    return divisor_sum == number

# Finding perfect numbers in a given range
def find_perfect_numbers(start, end):
    perfect_numbers = []
    for num in range(start, end + 1):
        if is_perfect_number(num):
            perfect_numbers.append(num)
    return perfect_numbers

# Taking input for range and finding perfect numbers
def check_perfect_numbers_in_range():
    start = int(input("Enter the starting number of the range: "))
    end = int(input("Enter the ending number of the range: "))
    perfect_numbers = find_perfect_numbers(start, end)
    if perfect_numbers:
        print("Perfect numbers in the range from", start, "to", end, "are:", perfect_numbers)
    else:
        print("There are no perfect numbers in the range from", start, "to", end)


check_perfect_numbers_in_range()

Example Output 1:

Enter the starting number of the range: 1

Enter the ending number of the range: 100

Perfect numbers in the range from 1 to 100 are: [6, 28]

Example Output 2:

Enter the starting number of the range: 10

Enter the ending number of the range: 25

There are no perfect numbers in the range from 10 to 25

Code Explanation:

The function is_perfect_number(number) checks whether a given number is a perfect number or not.

The function find_perfect_numbers(start, end) finds all the perfect numbers within a given range.

The function check_perfect_numbers_in_range() takes input for the range, finds perfect numbers within that range, and prints the result.